/*
 * DepartmentSaveServlet.java
 * Created on 25. juni 2008, 12:11
 */
package webshop.del;

import java.io.IOException;
import java.io.PrintWriter;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.UserTransaction;
import webshop.data.del.Department;



/**
 * DepartmentSaveServlet
 * @author even
 */
public class DepartmentSaveServlet  extends AbstractDepartmentServlet  {

    // We are going to change data, so we need a transaction
    @Resource
    UserTransaction tx;


    /**
     * Handle requests. Sends a html page containing the department list.
     *
     * @param req the request object
     * @param resp the response object
     *
     * @throws IOException
     * @throws ServletException
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        PrintWriter out = response.getWriter();
            
        response.setContentType("text/html");
        response.setHeader("Cache-control", "no-cache");
        response.setHeader("Expires", "0");

        out.println("<html><head><title>"+this.getClass().getName()+"</title></head><body>");
        out.println("<h1>Save Department</h1>");

        String name = request.getParameter("name");
        String no = request.getParameter("depno");
        EntityManager em = emf.createEntityManager();
        Department dep = null;

        try {
            // Transaction starts here
            tx.begin();
            
            if (no != null) {
                long depno = Long.valueOf(no);
                // edit existing department
                dep = em.find(Department.class, depno);
            }
            else {
                dep = new Department();
                em.persist(dep);
            }
            
            if (dep!=null) {
                dep.setName(name);
                // End of transaction - data will be saved
                // Any other path out of this method will
                // eventually roll back any changes
                tx.commit();
                out.println("Department saved!");
            }
            else out.println("Department no "+ no +" doesn't exist!");
            
        }
        catch (Exception e) {
            out.println("<p>Save department no "+no+" failed, because of:</p>");
            out.println("<pre>");
            e.printStackTrace(out);
            out.println("</pre>");
        }
        finally {
            em.close();
        }

        out.println("<hr/>");
        out.println("<p><a href=\"index.html\">Home</a> &gt; <a href=\"deplist\">Department List</a></p>");
        out.println("</body>");
        out.println("</html>");
    }
}
